import sys
import pdb
import threading
import MSLib as lib
CONFIG_FILE = 'safeinside.cfg'
lib.MSLogger.init(CONFIG_FILE)
log = lib.log
g_name = 'ms driver'
log.info(g_name + ' starting as %s' % (str(sys.argv)))

def processNormalObjects(isTerminated, database):
    log.info('processNormalObjects: started')

    try:
        cfg = lib.MSConfig.getConfig(CONFIG_FILE)
        reader = lib.MSDBReader(cfg.get('msdb', 'host'),
                                cfg.get('msdb', 'port'),
                                cfg.get('msdb', 'dbname'),
                                cfg.get('msdb', 'user'),
                                cfg.get('msdb', 'pwd'))
        reader.connect()

    except Exception, err:
        log.info('processNormalObjects: can\'t start: %s', str(err))
        return

    objects = {}
    ctr = 0

    try:
        while not isTerminated.isSet():
            if (ctr % 100 == 0):
                ctr = 0
                try:
                    lib.MSObjects.readObjectsFromMSDB(reader.connection.cursor(), objects, 'dev')
                    lib.MSObjects.readObjectsFromMSDB(reader.connection.cursor(), objects, 'fast')
                    log.info('processNormalObjects: loaded %d objects', len(objects))
                except Exception, err:
                    log.error('processNormalObjects: can\'t load objects: %s', str(err))
                log.info('processNormalObjects: status format: all:pgsm:cid:bolid:written')
            allevents = []
            eventsPGSM = None
            eventsContactId = None
            eventsBolid = None
            written = 0
            try:
                eventsPGSM = reader.getEventsPGSM(objects)
                allevents += eventsPGSM
                eventsContactId = reader.getEventsContactId(objects)
                allevents += eventsContactId
                eventsBolid     = reader.getEventsBolid(objects)
                allevents += eventsBolid
            except Exception, err:
                log.error('processNormalObjects: can\'t read events: %s', str(err))

            try:
                database.append(allevents)
            except Exception, err:
                log.error('processNormalObjects: can\'t write events: %s', str(err))

            log.info('processNormalObjects: %d:%d:%d:%d', len(eventsPGSM), len(eventsContactId), len(eventsBolid), written)
            ctr += 1
            if written == 0: lib.time.sleep(2)
    except Exception, err:
        log.error('processNormalObjects: fatal error: %s' % (str(err)))

log.info('starting threads... ')
isTerminated = threading.Event()
isTerminated.clear()
database = lib.MSRuntimeDatabase()

normalObjectsFromMSDB   = threading.Thread(target=processNormalObjects, name='normalObjectsFromMSDB', args=(isTerminated, database))
try:
    #start them
    normalObjectsFromMSDB.start()
    #check them
    lib.time.sleep(5)
    if not normalObjectsFromMSDB.isAlive(): raise RuntimeError('normalObjectsFromMSDB is not alive')
except Exception, err:
    log.error('can\'t start threads: ' + str(err))
    sys.exit(2)

log.info(g_name + ' started. Waiting for stop signal...')
try:
    while True:
        lib.time.sleep(2)
        database.cleanup()
except KeyboardInterrupt:
    log.info(g_name + ' stopping: %s' % (str(sys.argv)))
    sys.exit(0)
except Exception, err:
    log.error(g_name + ' stopping, fatal error: %s' % (str(err)))
    sys.exit(5)
finally:
    try:
        isTerminated.set()
        normalObjectsFromMSDB.join()
        log.info('stopped')
    except Exception, err:
        log.error('error while exiting: %s' % str(err))
        sys.exit(4)
